﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ContractManager.BLL.Business;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using System.Windows.Forms;
using ContractManager.Entity;
using DevExpress.XtraEditors;
using Speed.Data;

namespace ContractManager.Lists.Contracts
{
    public partial class FrmContractDetailDocuments : XtraFormBase
    {
        #region "Private Variable"
        private readonly BackgroundWorker _loadworker = new BackgroundWorker();
        public List<Employees> LstEmployees = new List<Employees>();
        public List<AttachedDocuments> LstAttachedDocuments = new List<AttachedDocuments>(); 

        public bool SaveClose;
        public bool SaveNew;
        public bool OnlyView;
        public int ConDetId;
        public int ConId;
        #endregion

        #region "Form Construction"
        public FrmContractDetailDocuments()
        {
            InitializeComponent();
            ClsVariable.DoubleBuffer(this);
            _loadworker.DoWork += loadworker_DoWork;
            _loadworker.RunWorkerCompleted += loadworker_RunWorkerCompleted;
        }
        #endregion

        #region "Private Method"
        private void BlankForm()
        {
            grdDetail.DataSource = ClsContractDetailDocuments.ListDetail(ConId,ConDetId);
        }

        public void GetData()
        {
            if (!_loadworker.IsBusy)
            {
                _loadworker.RunWorkerAsync();
                ClsVariable.SetWaitDialogCaption(string.Format("Nạp danh sách {0}...", Text));
            }
        }

        private void LoadLookupData()
        {
            EmpSearchLookUpEdit.DataSource = LstEmployees;
            EmpSearchLookUpEdit.DisplayMember = "FullName";
            EmpSearchLookUpEdit.ValueMember = "ID";
            AttachedDocumentSearchLookUpEdit.DataSource = LstAttachedDocuments;
            AttachedDocumentSearchLookUpEdit.DisplayMember = "AttDocName";
            AttachedDocumentSearchLookUpEdit.ValueMember = "AttDocId";
        }

        private void DoSave()
        {
            grdDetail.EmbeddedNavigator.Buttons.DoClick(grdDetail.EmbeddedNavigator.Buttons.EndEdit);
            DataTable dtSource = (DataTable)grdDetail.DataSource;

            var listAdd = GetListAdd(dtSource.GetChanges(DataRowState.Added));
            var listUpdate = GetListUpdate(dtSource.GetChanges(DataRowState.Modified));
            var listDelete = GetListDelete(dtSource.GetChanges(DataRowState.Deleted));

            try
            {
                using (var db = Sys.NewDb())
                {
                    db.BeginTransaction();
                    foreach (var addItem in listAdd)
                    {
                        db.Insert<ContractDetailDocuments>(addItem);
                    }
                    foreach (var updateItem in listUpdate)
                    {
                        db.Update<ContractDetailDocuments>(updateItem);
                    }
                    foreach (var delItem in listDelete)
                    {
                        db.Delete<ContractDetailDocuments>(string.Format("ConDetDocId={0}", delItem.ConDetDocId));
                    }
                    db.Commit();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                    String.Format("Có lỗi xảy ra trong quá trình cập nhật dữ liệu. {0}", ex.Message),
                    "Thông báo",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private List<ContractDetailDocuments> GetListAdd(DataTable dataTable)
        {
            List<ContractDetailDocuments> list = new List<ContractDetailDocuments>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    ContractDetailDocuments item = new ContractDetailDocuments();
                    item.ConDetDocId = 0;
                    item.ConDetId = ConDetId;
                    if (!row.IsNull("AttDocId") && row["AttDocId"] != DBNull.Value)
                    {
                        item.AttDocId = Convert.ToInt32(row["AttDocId"]);
                    }
                    item.ConDetDocQuantity = row["ConDetDocQuantity"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetDocQuantity"]);
                    item.ConDetDocDescription = String.Format("{0}", row["ConDetDocDescription"]);
                    item.ConDetDocPosition = String.Format("{0}", row["ConDetDocPosition"]);
                    item.ConDetDocStatus = String.Format("{0}", row["ConDetDocStatus"]);
                    if (!row.IsNull("ConDetDocDate") && row["ConDetDocDate"] != DBNull.Value)
                    {
                        item.ConDetDocDate = Convert.ToDateTime(row["ConDetDocDate"]);
                    }
                    item.ConDetDocNumberCopy = row["ConDetDocNumberCopy"] == DBNull.Value ? 0 : Convert.ToInt32(row["ConDetDocNumberCopy"]);
                    if (!row.IsNull("EmpId") && row["EmpId"] != DBNull.Value)
                    {
                        item.EmpId = Convert.ToInt32(row["EmpId"]);
                    }
                    if (!row.IsNull("ConDetDocDateBorrow") && row["ConDetDocDateBorrow"] != DBNull.Value)
                    {
                        item.ConDetDocDateBorrow = Convert.ToDateTime(row["ConDetDocDateBorrow"]);
                    }
                    item.CustomField1 = String.Format("{0}", row["CustomField1"]);
                    item.CustomField2 = String.Format("{0}", row["CustomField2"]);
                    item.CustomField3 = String.Format("{0}", row["CustomField3"]);
                    item.CustomField4 = String.Format("{0}", row["CustomField4"]);
                    item.CustomField5 = String.Format("{0}", row["CustomField5"]);

                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<ContractDetailDocuments> GetListUpdate(DataTable dataTable)
        {
            List<ContractDetailDocuments> list = new List<ContractDetailDocuments>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    ContractDetailDocuments item = new ContractDetailDocuments();
                    item.ConDetDocId = Convert.ToInt32(row["ConDetDocId"]);
                    item.ConDetId = Convert.ToInt32(row["ConDetId"]);
                    if (!row.IsNull("AttDocId") && row["AttDocId"] != DBNull.Value)
                    {
                        item.AttDocId = Convert.ToInt32(row["AttDocId"]);
                    }
                    item.ConDetDocQuantity = row["ConDetDocQuantity"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetDocQuantity"]);
                    item.ConDetDocDescription = String.Format("{0}", row["ConDetDocDescription"]);
                    item.ConDetDocPosition = String.Format("{0}", row["ConDetDocPosition"]);
                    item.ConDetDocStatus = String.Format("{0}", row["ConDetDocStatus"]);
                    if (!row.IsNull("ConDetDocDate") && row["ConDetDocDate"] != DBNull.Value)
                    {
                        item.ConDetDocDate = Convert.ToDateTime(row["ConDetDocDate"]);
                    }
                    item.ConDetDocNumberCopy = row["ConDetDocNumberCopy"] == DBNull.Value ? 0 : Convert.ToInt32(row["ConDetDocNumberCopy"]);
                    if (!row.IsNull("EmpId") && row["EmpId"] != DBNull.Value)
                    {
                        item.EmpId = Convert.ToInt32(row["EmpId"]);
                    }
                    if (!row.IsNull("ConDetDocDateBorrow") && row["ConDetDocDateBorrow"] != DBNull.Value)
                    {
                        item.ConDetDocDateBorrow = Convert.ToDateTime(row["ConDetDocDateBorrow"]);
                    }
                    item.CustomField1 = String.Format("{0}", row["CustomField1"]);
                    item.CustomField2 = String.Format("{0}", row["CustomField2"]);
                    item.CustomField3 = String.Format("{0}", row["CustomField3"]);
                    item.CustomField4 = String.Format("{0}", row["CustomField4"]);
                    item.CustomField5 = String.Format("{0}", row["CustomField5"]);

                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<ContractDetailDocuments> GetListDelete(DataTable dataTable)
        {
            List<ContractDetailDocuments> list = new List<ContractDetailDocuments>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    ContractDetailDocuments item = new ContractDetailDocuments();
                    item.ConDetDocId = Convert.ToInt32(row["ConDetDocId", DataRowVersion.Original]);
                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        #endregion

        #region "Background Worker"

        private void loadworker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                LstEmployees = ClsEmployees.SelectAll();
                LstAttachedDocuments = ClsAttachedDocuments.SelectAll();
                e.Result = LstEmployees;
            }
            catch (Exception)
            {
                e.Cancel = true;
            }
        }

        private void loadworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Action a = LoadLookupData;
            grdDetail.Invoke(a);
            ClsVariable.SetWaitDialogCaption(string.Format("Danh sách {0} đã được nạp", Text));
        }
        #endregion

        #region "Form Event"
        private void FrmContractDetailDocumentsLoad(object sender, EventArgs e)
        {
            BlankForm();
            GetData();
            btnSave.Enabled = ConDetId>0;
            btnDesign.Enabled = !OnlyView;
            grvDetail.OptionsBehavior.Editable = ConDetId > 0;
            //if (!String.IsNullOrEmpty(FormXtraGridLayoutTemplate))
            //{
            //    var filePath = ClsVariable.GetRestoreLayoutFullPath(FormXtraGridLayoutTemplate);
            //    grvDetail.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
            //}
        }
        #endregion

        #region "Toolbar Event"
        private void TbMenuItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "btnSave":
                    DoSave();
                    break;
                case "btnSaveNew"://Lưu và thêm mới
                    SaveNew = true;
                    DoSave();
                    break;
                case "btnSaveClose"://Lưu và đóng
                    SaveClose = true;
                    DoSave();
                    break;
                case "btnDesign":
                    ClsVariable.ShowDesignXtraGrid(grdDetail);
                    break;
                case "btnClose":
                    Close();
                    break;
            }
        }
        #endregion

        

        
    }
}
